package com.gaimall.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.springframework.stereotype.Service;

import com.gaimall.beans.xmlbean.Data;
import com.gaimall.beans.xmlbean.Filter;
import com.gaimall.beans.xmlbean.Goods;
import com.gaimall.beans.xmlbean.Goods_idsearch;
import com.gaimall.beans.xmlbean.Item;
import com.gaimall.beans.xmlbean.Result;
import com.gaimall.beans.xmlbean.Result_idsearch;
import com.gaimall.beans.xmlbean.Result_recom;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

@Service
public class ApiService {
	/**
	 * 返回GenralSearch搜索结果
	 * 
	 * @param qword
	 * @param page
	 * @return
	 */
	public Result getResult(String kw, String page, String sorter, String type, String brand,
			String source) {
		Result rs = null;
		String xml = this.invokeGeneralSearch(kw, page, sorter, type, brand, source);
		XStream xstream = new XStream(new StaxDriver());
		xstream.alias("result", Result.class);
		xstream.alias("filter", Filter.class);
		xstream.alias("goods", Goods.class);

		xstream.aliasAttribute(Goods.class, "standard__name", "standard-name");
		xstream.aliasAttribute(Goods.class, "sales__volume", "sales-volume");
		xstream.aliasAttribute(Goods.class, "pic__url", "pic-url");
		xstream.aliasAttribute(Goods.class, "price__history", "price-history");

		xstream.aliasAttribute(Result.class, "time", "time");
		xstream.aliasAttribute(Result.class, "length", "length");

		if (!"".equals(xml)) {
			rs = (Result) xstream.fromXML(xml);
		}
		return rs;

	}

	/**
	 * 返回IdSearch搜索结果
	 * 
	 * @param qword
	 * @param page
	 * @return
	 */
	public Result_idsearch getResult_IdSearch(String id, String page) {
		Result_idsearch rs = null;
		String xml = this.invokeIdSearch(id, page);
		XStream xstream = new XStream(new StaxDriver());
		xstream.alias("result", Result_idsearch.class);
		// xstream.alias("filter", Filter.class);
		xstream.alias("goods", Goods_idsearch.class);

		xstream.aliasAttribute(Goods_idsearch.class, "standard_name", "standard-name");
		xstream.aliasAttribute(Goods_idsearch.class, "sales_volume", "sales-volume");
		xstream.aliasAttribute(Goods_idsearch.class, "pic_url", "pic-url");
		xstream.aliasAttribute(Goods_idsearch.class, "second_type", "second-type");
		xstream.aliasAttribute(Goods_idsearch.class, "filter_all", "filter-all");
		xstream.aliasAttribute(Goods_idsearch.class, "filter_each", "filter-each");
		xstream.aliasAttribute(Goods_idsearch.class, "price_history", "price-history");

		xstream.aliasAttribute(Result_idsearch.class, "time", "time");
		xstream.aliasAttribute(Result_idsearch.class, "length", "length");

		if (!"".equals(xml)) {
			rs = (Result_idsearch) xstream.fromXML(xml);
		}
		return rs;

	}

	/**
	 * 返回分页链接
	 * 
	 * @param currentPageNo
	 * @param maxPageNo
	 * @param qword
	 * @return
	 */
	public String getPagelink(int currentPageNo, int maxPageNo, String kw, String mapping,
			String r_type, String r_source, String r_brand, String sorter) {

		StringBuffer sb = new StringBuffer("");

		try {
			kw = URLEncoder.encode(kw, "UTF-8");

			if (r_type != null && !"".equals(r_type)) {
				r_type = URLEncoder.encode(r_type, "UTF-8");
				sb.append("&type=" + r_type);
			}

			if (r_brand != null && !"".equals(r_brand)) {
				r_brand = URLEncoder.encode(r_brand, "UTF-8");
				sb.append("&brand=" + r_brand);
			}

			if (r_source != null && !"".equals(r_source)) {
				r_source = URLEncoder.encode(r_source, "UTF-8");
				sb.append("&source=" + r_source);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}

		currentPageNo = currentPageNo > maxPageNo ? maxPageNo : currentPageNo;
		int begainNo = currentPageNo - 5 > 0 ? currentPageNo - 5 : 1;
		int endNo = begainNo + 9 > maxPageNo ? maxPageNo : begainNo + 9;
		StringBuffer bf = new StringBuffer();
		if (maxPageNo > 1) {
			bf.append(begainNo > 1 ? ("<a href = \"/gaimall" + mapping + "?kw=" + kw + "&page="
					+ (currentPageNo - 1 > 1 ? currentPageNo - 1 : 1) + "&sorter="+sorter
					+ sb.toString() + "\" class=\"next-button\">上一页</a>&nbsp") : "");
			for (int i = begainNo; i <= endNo; i++) {

				if (i == currentPageNo) {

					bf.append("<a href = \"/gaimall" + mapping + "?kw=" + kw + "&page=" + i
							+ "&sorter="+sorter + sb.toString() + "\" class=\"pressed-button\">"
							+ i + "</a>&nbsp");
				} else
					bf.append("<a href = \"/gaimall" + mapping + "?kw=" + kw + "&page=" + i
							+ "&sorter=" +sorter + sb.toString() + "\" class=\"page-button\">" + i
							+ "</a>&nbsp");
			}
			bf.append(endNo < maxPageNo ? ("<a href = \"/gaimall" + mapping + "?kw=" + kw
					+ "&page="
					+ (currentPageNo + 1 > maxPageNo ? maxPageNo : currentPageNo + 1)
					+ "&sorter="+sorter + sb.toString() + "\" class=\"next-button\">下一页</a>") : "");
			return bf.toString();
		}
		return "";

	}

	/**
	 * 返回推荐搜索结果
	 * 
	 * @param id
	 * @return
	 */
	public Result_recom getResult_recom(String id) {
		Result_recom rr = null;
		String xml = this.invokeRecomSearch(id); 
		XStream xstream = new XStream(new StaxDriver());

		xstream.aliasAttribute(Data.class, "type", "type");
		xstream.alias("result", Result_recom.class);
		xstream.alias("data", Data.class);
		xstream.alias("item", Item.class);
		
		xstream.processAnnotations(Result_recom.class);
		xstream.processAnnotations(Data.class);
		xstream.processAnnotations(Item.class);

		if (!"".equals(xml)) {
			rr = (Result_recom) xstream.fromXML(xml);
		}
		return rr;

	}
	
	/**
	 * 调用General接口
	 * 
	 * @param kw
	 * @param currentPageNo
	 * @param sorter
	 * @param type
	 * @param brand
	 * @param source
	 * @return
	 */
	private String invokeGeneralSearch(String kw, String currentPageNo, String sorter,
			String type, String brand, String source) {
		StringBuffer xml = new StringBuffer("");
		try {
			String urlencoded_kw = URLEncoder.encode(kw, "UTF-8");
			StringBuffer url_string = new StringBuffer();
			url_string.append("http://api.fanmi.cn/shopping/search?searcher=generalSearch&num=36&keyword="
					+ urlencoded_kw + "&page=" + currentPageNo + "&sorter=" + sorter);
			if (type != null && !"".equals(type)) {
				url_string.append("&filter_type_same=" + URLEncoder.encode(type, "UTF-8"));
			}

			if (brand != null && !"".equals(brand)) {
				url_string.append("&filter_brand_fc=" + URLEncoder.encode(brand, "UTF-8"));
			}

			if (source != null && !"".equals(source)) {
				url_string.append("&filter_source_fc=" + URLEncoder.encode(source, "UTF-8"));
			}
			URL url = new URL(url_string.toString());
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),
					"UTF-8"));
			String s;
			while ((s = in.readLine()) != null) {
				xml.append(s);
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml.toString();
	}

	/**
	 * 调用IdSearch接口
	 * 
	 * @param kw
	 * @param currentPageNo
	 * @param sorter
	 * @param type
	 * @param brand
	 * @param source
	 * @return
	 */
	private String invokeIdSearch(String id, String currentPageNo) {
		StringBuffer xml = new StringBuffer("");
		try {
			// String urlencoded_kw = URLEncoder.encode(kw, "UTF-8");
			StringBuffer url_string = new StringBuffer();
			url_string.append("http://api.fanmi.cn/shopping/search?searcher=idSearch&num=10&keyword="
					+ id + "&page=" + currentPageNo + "&sorter=1");
			URL url = new URL(url_string.toString());
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),
					"UTF-8"));
			String s;
			while ((s = in.readLine()) != null) {
				xml.append(s);
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml.toString();
	}

	/**
	 * 调用相关产品接口
	 * 
	 * @param kw
	 * @param currentPageNo
	 * @param sorter
	 * @param type
	 * @param brand
	 * @param source
	 * @return
	 */
	private String invokeRecomSearch(String id) {
		StringBuffer xml = new StringBuffer("");
		try {
			StringBuffer url_string = new StringBuffer();
			url_string.append("http://api.fanmi.cn/recom/recom?id=" + id + "&tps=91_3,92_3,93_8");

			URL url = new URL(url_string.toString());
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),
					"UTF-8"));
			String s;
			while ((s = in.readLine()) != null) {
				xml.append(s);
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml.toString();
	}

}
